<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="配置"
      draggable
      :width="isMobile ? '95%' : '75%'"
      :before-close="handleClose"
    >
      <div class="contents">
        <!-- 左侧树形区域 -->
        <div class="contents-left" :class="{ 'mobile-hidden': isMobile && !showTree }">
          <!-- 左侧头部和搜索区域 -->
          <div class="left-header">
            <el-button type="primary" size="small" @click="toggleExpand">
              {{ isExpanded ? "收起" : "展开" }}
            </el-button>
            <el-dropdown placement="bottom-start">
              <el-button size="small">选择</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="setCheckedKeys">全选</el-dropdown-item>
                  <el-dropdown-item @click="setCheckedKeysShow">反选</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-select
              v-model="isBd"
              size="small"
              @change="getbtnpi(isBd)"
              style="width: 100px">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @click.native="btnpi()"
              />
            </el-select>
          </div>

          <div class="inputs">
            <el-input
              v-model="input1"
              size="small"
              placeholder="输入关键字进行过滤"
              :suffix-icon="Search"
            />
          </div>

          <!-- 树形组件 -->
          <div class="tree-container">
            <el-tree
              ref="treeRef"
              :data="treeData || data"
              show-checkbox
              node-key="id"
              highlight-current
              :props="defaultProps"
              :default-expand-all="expandShow"
              :check-strictly="false"
              @check-change="handleCheckChange"
              v-loading="treeLoading"
              element-loading-text="加载中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 1)"
            >
              <!-- 自定义树节点内容 -->
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span class="tree-checkbox-wrapper" @click.stop>
                    <el-checkbox
                      :model-value="node.checked"
                      :indeterminate="node.indeterminate"
                      @change="(val) => handleCheckboxChange(val, node)"
                      @click.stop
                    />
                  </span>
                  <span class="tree-label" @click.stop="handleLabelClick(data)">
                    <div class="label-text">{{ node.label }}</div>
                    <div class="names" v-if="data.categorySaveClass">
                      {{data.categorySaveClass}}
                    </div>
                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>

        <!-- 右侧表格区域 -->
        <div class="contents-right">
          <div class="mobile-tree-toggle" v-if="isMobile" @click="showTree = !showTree">
            <el-icon>
              <component :is="showTree ? 'ArrowLeft' : 'ArrowRight'" />
            </el-icon>
            {{ showTree ? '隐藏树' : '显示树' }}
          </div>

          <div class="header">
            <el-form :inline="!isMobile" :modhandleTableClickel="form1" class="demo-form-inline">
              <el-form-item label="查询条件" :style="isMobile ? 'width:100%' : ''">
                <el-input
                  v-model="form1._key_word"
                  placeholder="请输入平台名称"
                  clearable
                  size="small"
                />
              </el-form-item>

              <el-form-item :style="isMobile ? 'width:100%' : ''">
                <el-button @click="getSetdocking" size="small">查询</el-button>
              </el-form-item>
            </el-form>
          </div>

          <div class="table-area">
            <el-dropdown size="small" style="margin-bottom: 10px;" split-button type="primary" @click="handleTableClick" @command="handleCommand">
                  {{dropdownData}}
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="批量对接">批量对接</el-dropdown-item>
                      <el-dropdown-item command="批量自营">批量自营</el-dropdown-item>

                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
            <el-table
             @selection-change="handleSelectionChange"
              border
              :data="selectedItems"
              v-loading="tableLoading"
              element-loading-text="加载中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.7)"
              style="width: 100%"
            >
            <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="商品编号" width="100"  />
              <el-table-column prop="goods_name" label="商品名称" min-width="120">
                  <template #default="scope">
                    <el-tooltip
                      effect="dark"
                      :content="scope.row.goods_name"
                      placement="top"
                      :disabled="!shouldShowTooltip(scope.row.goods_name)"
                    >
                      <div class="ellipsis-cell">{{ scope.row.goods_name }}</div>
                    </el-tooltip>
                  </template>
                </el-table-column>



              <el-table-column prop="_goods_type_text" label="商品类型" width="100" align="center" />
              <el-table-column prop="join_price" label="购买价格" width="100" align="center" />
              <el-table-column label="状态" width="80" align="center">
                <template #default="scope">
                  {{ scope.row.status == 1 ? "正常" : "下架" }}
                </template>
              </el-table-column>
              <el-table-column prop="stock_num" label="库存" width="80" align="center" />
              <el-table-column label="对接状态" width="100" align="center">
                <template #default="scope">
                  <el-button
                    :disabled="scope.row._has_join"
                    :type="scope.row._has_join ? '' : 'danger'"
                    size="small"
                    @click="btnpi2(scope.row.id)"
                  >
                    {{ scope.row._has_join ? '已对接' : '未对接' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="prev, pager, next, sizes, total"
                :total="total"
                small
              />

            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel" size="small">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量对接商品对话框 -->
    <el-dialog
      v-model="shoppingShow"
      draggable 
      :title="titleName"
      :width="isMobile ? '90%' : '36%'"
      :before-close="handleClose"
    >
      <div>
        <el-form
          :label-position="isMobile ? 'top' : 'right'"
          label-width="100px"
          :model="formLabelAlign"
        >
		<view >


      <!-- <el-select
								    v-model="formLabelAlign.cate_id"
								    :style="isMobile ? 'width:100%' : 'width:192px'"
								    placeholder="请选择"
								    size="small"
                    @change="jiajia"
								  >
								    <el-option
								      v-for="item in dockingMenuList"
								      :key="item.id"
								      :label="item.name"
								      :value="item.id"
								    />
								  </el-select> -->


			<el-form-item  label="商品目录" v-if="isBd==4||isBd==5" v-show="shopping">
								
								
        <el-select
          v-model="formLabelAlign.cate_id"
          :style="isMobile ? 'width:100%' : 'width:192px'"
          placeholder="请选择"
          size="small"
          @change="jiajia"
        >
          <!-- 每个 el-option 单独绑定 Tooltip -->
          <el-option
            v-for="item in dockingMenuList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
            <!-- ✅ Tooltip 放在 el-option 默认插槽内 -->
            <el-tooltip
              effect="dark"
              placement="right"  
              :content="`${item.name}`"  
            >
              <span>{{ item.name }}</span>  <!-- 保证正常显示选项名称 -->
            </el-tooltip>
          </el-option>
        </el-select>

			</el-form-item>
			<el-form-item  label="加价模版" v-if="isBd !==3">
    
        <el-select
          v-model="formLabelAlign.priceName_id"
          :style="isMobile ? 'width:100%' : 'width:192px'"
          placeholder="请选择加价模版"
          size="small"
          @change="jiajia"
        >
          <!-- 每个 el-option 单独绑定 Tooltip -->
          <el-option
            v-for="item in goodPriceReadyList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
            <!-- ✅ Tooltip 放在 el-option 默认插槽内 -->
            <el-tooltip
              effect="dark"
              placement="right"  
              :content="`${item.name}`"  
            >
              <span>{{ item.name }}</span>  <!-- 保证正常显示选项名称 -->
            </el-tooltip>
          </el-option>
        </el-select>

        
        <el-button @click="addPrice" style="margin-left: 12px;" type="primary" size="small">添加模版</el-button>
			</el-form-item>
		</view>
		<view >
			
			<el-form-item v-if="ispldj||isDropdown" label="商品目录">
        <el-tree-select
  node-key="id"
  v-model="formLabelAlign.cate_ids"
  :data="dockingMenuList"
  :props="{ label: 'name', children: '_child_list' }"
  :render-content="(h, params) => renderTreeNode(h, params)"
  show-checkbox
  multiple
  :check-strictly="false"
  :style="isMobile ? 'width:100%' : 'width:192px'"
  @check="handleCheck"
/>

               
			</el-form-item>
			
			<el-form-item label="加价模版" v-show="modelShow">
			  <el-select
			    v-model="formLabelAlign.priceName_id"
			    :style="isMobile ? 'width:100%' : 'width:192px'"
			    placeholder="请选择加价模版"
			    size="small"
			  >
			    <el-option
			      v-for="item in goodPriceReadyList"
			      :key="item.id"
			      :label="item.name"
			      :value="item.id"
			    />
			  </el-select>
			</el-form-item>
		</view>
		

          <div class="image-options">
            <span>图片保存方式：</span>
            <el-radio-group v-model="radio" @change="changeUrl">
              <el-radio :label="3">获取对方地址</el-radio>
              <el-radio :label="6">{{imgName}}</el-radio>
              <el-radio :label="9">自定义图片</el-radio>
            </el-radio-group>

            <div v-show="radio == 9" class="upload-area">
              <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                :http-request="httpRequest" 
                multiple
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="handleUploadSuccess"
                :limit="3"
                :on-exceed="handleExceed"
              >
                <el-button type="primary" size="small">上传图片</el-button>
              </el-upload>
            </div>
          </div>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="shoppingShow = false" size="small">取消</el-button>
          <el-button type="primary" @click="addDockGood()" size="small">确定</el-button>
        </div>
      </template>
    </el-dialog>

       <!-- 定价模版新增 -->
       <el-dialog
      v-model="priceShow"
      :show-close="false"
      draggable
      title="添加"
      width="56%"
    >
      <div class="img-area">
        <div>
          <div class="jibies">
            <el-form-item label="模版名称" style="margin-left: 28px;">
              <el-input v-model="input2" style="width: 500px" />
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="区间开始金额">
              <el-input v-model="input2" style="width: 500px" />
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="区间结束金额">
              <el-input v-model="input2" style="width: 500px" />
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="级别差价" style="margin-left: 28px;">
              <el-input v-model="input2" style="width: 500px" />
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="定价策略" style="margin-left: 28px;">
              <el-input v-model="input2" style="width: 500px" />
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="我的利润" style="margin-left: 28px;">
              <el-input v-model="input2" style="width: 500px" />
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="一级服务商" style="margin-left: 12px;">
              <el-input v-model="input2" style="width: 500px">
                <template #append>元 + 商品销售价</template>
              </el-input>
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="尊贵铂金" style="margin-left: 28px;">
              <el-input v-model="input2" style="width: 500px">
                <template #append>元 + 商品销售价</template>
              </el-input>
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="荣耀黄金" style="margin-left: 28px;">
              <el-input v-model="input2" style="width: 500px">
                <template #append>元 + 商品销售价</template>
              </el-input>
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="秩序白银" style="margin-left: 28px;">
              <el-input v-model="input2" style="width: 500px">
                <template #append>元 + 商品销售价</template>
              </el-input>
            </el-form-item>
          </div>
          <div class="jibies">
            <el-form-item label="普通会员" style="margin-left: 28px;">
              <el-input v-model="input2" style="width: 500px">
                <template #append>元 + 商品销售价</template>
              </el-input>
            </el-form-item>
          </div>
        </div>
		
      </div>
	  <div style="display: flex;justify-self: center;">
			<el-button type="primary" plain @click="mobanClose">取消</el-button>
            <el-button type="primary">保存</el-button>
		</div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>



import { h } from 'vue'
import { ElTooltip } from 'element-plus'

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx"
import { ref, watch, nextTick, onMounted ,onBeforeUnmount, computed} from "vue";
import type { ElTree } from "element-plus";
import { ElMessageBox, ElMessage, ElLoading } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  uploads
} from "~/base/api/product/productList.ts";
import {
  categorygoodlist,
  getLocalCatePage,
  getGoodPriceReadyList,
  addDockGoods,
  categorySave,
  AddDock,
  isBind7NiuYun
} from "~/base/api/goods/channel";

interface Tree {
  id: number;
  label: string;
  children?: Tree[];
}const valueStrictly = ref()
const dropdownData=ref('批量对接')
const customProps = {
  value: 'id',       // 指定节点值对应的字段名
  label: 'name',     // 指定显示文本对应的字段名
  children: '_child_list',  // 指定子节点对应的字段名

}
const renderTreeNode = (h, { node, data }) => {
  if (!node || !data) return h('span', '加载中...')
  
  // 方案1：使用组件模式（推荐）
  return h('div', { class: 'custom-node' }, [
    h(ElTooltip, { // 必须直接使用导入的ElTooltip组件
      props: {
        effect: 'dark',
        placement: 'right',
        content: data.name
      }
    }, [
      h('span', node.label)
    ])
  ])

}



const shopping =ref(true)
const titleName=ref("")
const priceShow=ref(false)
// 添加响应式检测
const isMobile = ref(false)
const showTree = ref(true) // 移动端默认显示树
// 添加 tableLoading 状态
const modelShow=ref(true)
const tableLoading = ref(false);
const treeLoading = ref(false);
const ispldj = ref(true);
const cate_ids=ref()
const formLabelAlign = ref({
  priceName_id: "",
  id: "",
  goods_attment_face_id: "",
  cate_ids:[],
  cate_id: [],
  Docking: "",
});
const handleCheck = (checkedNodes: any, checkedKeys: any) => {
  console.log('选中的节点:', checkedNodes);
  console.log('选中的键:', checkedKeys);
  let checkList=[]
  checkedNodes.map(x=>{
    checkList.push(x.id)
  })
  checkedKeys=checkList
  formLabelAlign.value.cate_ids = checkList;
};
const options = [
  {
    value: 2,
    label: '一键对接',
  },
  {
    value: 1,
    label: '一键本地',
  },
  {
    value: 3,
    label: '克隆全部分类',
  },  {
    value: 4,
    label: '对接分类和商品',
  },
  {
    value: 5,
    label: '克隆分类和商品',
  },

]
const handleCateIdsChange = (value: number[]) => {
  valueStrictly = value;
  console.log('选中的分类ID:', value);
};
const isDropdown=ref(false)
// 下拉菜单选择事件
const handleCommand = (command: string | number | object) => {
    dropdownData.value=command
    handleTableClick()
}
const handleTableClick = () => {
  shopping.value=false
    isDropdown.value=true

  if(selectedItems.value.length==0){
        ElMessage.error("请先点击商品分类");
        return
  }
  if(multipleSelection.value.length==0){
     ElMessage.error("请先选择商品");
     return
  }
  // isDropdown.value=true
  btnpi()
  
}
const toOss=ref("")
const isBd=ref(2)
const imgName=ref("未配置OSS")
const categoryForm = ref({
  id: "",
  color: "",
  name: "",
  parent_id: 0,
  status: 1,
  pub_status: 1,
  istop: 1,
  info: "",
  toOss:"",
  dockid: "",
  dockid_info: 1,
  img: "",
});
const categoryForm2 = ref({
  id: "",
  color: "",
  name: "",
  parent_id: 0,
  status: 1,
  pub_status: 1,
  istop: 1,
  info: "",
  dockid: "",
  toOss:"",
  dockid_info: "",
  img: "",
});
const formInline2 = ref({
  name: "",
});
const radio = ref(3);
const labelPosition = ref("right");
const shoppingShow = ref(false);
// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dockingMenuList = ref([]);
const goodPriceReadyList = ref([]);

const treeRef = ref<InstanceType<typeof ElTree>>();
const isExpanded = ref(true);
const input1 = ref("");
const treeLoaded = ref(false); // 标记树是否已加载
const selectedItems = ref([]);



// 接收父组件参数
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },

  dockId: {
    type: String,
    default: "",
  },
  treeData: {
    type: Array,
    default: () => [],
  },

});
const httpRequest = async (options) => {
  try {
    const formData = new FormData();
    formData.append('file', options.file);
    
    // 调用你的API接口
    const res = await uploads(formData);
    
    if (res.code === 200) {
      options.onSuccess(res.data); // 必须调用以更新文件列表状态
      return res;
    } else {
      options.onError(new Error(res.message));
    }
  } catch (err) {
    options.onError(err);
  }
};




const fontData = ref({}); //存点击文字时文字的data
const emit = defineEmits(["update:modelValue", "confirm"]);
const dockIds = ref("");
const defaultProps = {
  children: "list",
  label: "name",
};
const form1 = ref({});
const form2 = ref({});
const checkedNodesAll = ref([]);
const dialogVisible = ref(false);
const mobanShow=ref("")
const expandShow = ref(false);
const multipleSelection = ref<User[]>([])
//下拉加价模块
function jiajia(e){
  console.log(e)
  mobanShow.value=e
}
const dockId = ref(props.dockId); // 新增：定义dockId响应式变量
const checkIsMobile = () => {
  isMobile.value = window.innerWidth <= 768
  // 如果是移动端且对话框刚打开，默认隐藏树
  if (isMobile.value && dialogVisible.value) {
    showTree.value = false
  }
}
// table 多选
const handleSelectionChange = (val: User[]) => {
  console.log('multipleSelection.value ',val)
  multipleSelection.value = val
}
//上传图片
const fileList = ref<UploadUserFile[]>([]);
// 上传成功处理
const handleUploadSuccess = (
  response: any,
  file: UploadFile,
  fileList: UploadFiles
) => {
  console.log("上传成功:", response.data.url);
  // 通常后端会返回图片URL或其他标识
  formLabelAlign.value.goods_attment_face_id = response.data.url;
  categoryForm.value.img = imgListsting.value;
  console.log("上传成功:", formLabelAlign.value);
};
const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(111111111111, uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  console.log("上传", files);
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};
const changeUrl = (value) => {
  console.log("value", value);
  if (value == 3 || value == 9) {
    formLabelAlign.value.goods_attment_face_id = "";
    toOss.value=''
  } else if (value == 6) {
    toOss.value='1'
    formLabelAlign.value.goods_attment_face_id = "isSaveToLocal";
  }
};
// 分类和商品
//父级调用categorySave  这里需要看多选，变成遍历的
async function parentCategorySave_isBd4() {
  // 1. 保存当前选中状态
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];
console.log(checkDataList.value)
let lest=[]
checkDataList.value.map(x=>{
	lest.push(...x.list)
})
console.log(lest)
let parent_ids=formLabelAlign.value.cate_id
let priceName_ids=formLabelAlign.value.priceName_id
  for (const [index, x] of lest.entries()) {
    let form = {
		cate_id:[parent_ids],
	priceName_id:priceName_ids,
      id: "",
      color: "",
      name: x.name,
      parent_id: parent_ids ,
      status: 1,
      pub_status: 1,
      istop: 1,
      info: "",
      toOss:toOss.value,
      dockid: dockIds.value,
      dockid_info: x.id,
      img: imgListsting.value,
    };

    try {
      // 等待父级保存完成
  
	await	childCategorySave_isBd4(form,x.id)
      
    } catch (error) {
      console.error(`处理父项 ${x.id} 失败:`, error);
      // 继续处理下一个父项
      continue;
    }
  }
}
// 子级保存函数（修改为异步）
async function childCategorySave_isBd4(datas, parentId) {
  // 1. 保存当前选中状态
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];

  try {
    // 1. 保存子类
    const saveRes = await categorySave(datas);

    if (saveRes.code !== 200) {
      throw new Error("子类保存失败");
    }

    ElMessage.success("新增成功");

    const childClassId = saveRes.data.classid;
    emit('update-node', {
      id: datas.dockid_info,
      property: 'categorySaveClass',
      value: childClassId
    });

    // 3. 恢复选中状态
    nextTick(() => {
      treeRef.value?.setCheckedKeys(checkedKeys);
      halfCheckedKeys.forEach(key => {
        const node = treeRef.value?.getNode(key);
        if (node) {
          treeRef.value?.setChecked(key, false, false);
        }
      });
    });


    // 4. 获取商品列表（如果有）
    const form11 = {
      id: dockIds.value,
      class: datas.classid,
      listid: parentId,
      page: currentPage.value,
      limit: 100,
    }
console.log(111111111122,form11)
    const listRes = await categorygoodlist(form11);

    // 修改这里：不再把"暂无数据"当作错误
    if (listRes.code === 200 || listRes.code === 1) {
		
      selectedAllItems.value = listRes.code === 200 ? listRes.data.data : [];
      selectedItems.value = listRes.code === 200 ? listRes.data.data : [];

      if (selectedAllItems.value.length !== 0) {
        await addPLDockGood(childClassId, form11);
      }
    } else {
      console.error("获取商品列表失败:", listRes.message);
    }
  } catch (error) {
    console.error("子级保存失败:", error);
    ElMessage.error("操作失败: " + error.message);
    throw error;
  }
}

async function parentCategorySave_isBd5() {
  // 1. 保存当前选中状态
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];
console.log(checkDataList.value)
let lest=[]
checkDataList.value.map(x=>{
	lest.push(...x.list)
})
console.log(lest)
let parent_ids=formLabelAlign.value.cate_id
let priceName_ids=formLabelAlign.value.priceName_id
  for (const [index, x] of lest.entries()) {
    let form = {
		cate_id:[parent_ids],
	priceName_id:priceName_ids,
      id: "",
      color: "",
      name: x.name,
      parent_id: parent_ids ,
      status: 1,
      pub_status: 1,
      istop: 1,
      info: "",
      toOss:toOss.value,
      dockid: dockIds.value,
      dockid_info: x.id,
      img: imgListsting.value,
      provide_type: ""
    };

    try {
      // 等待父级保存完成
  
	await	childCategorySave_isBd5(form,x.id)
      
    } catch (error) {
      console.error(`处理父项 ${x.id} 失败:`, error);
      // 继续处理下一个父项
      continue;
    }
  }
}
// 子级保存函数（修改为异步）
async function childCategorySave_isBd5(datas, parentId) {
  // 1. 保存当前选中状态
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];

  try {
    // 1. 保存子类
    const saveRes = await categorySave(datas);

    if (saveRes.code !== 200) {
      throw new Error("子类保存失败");
    }

    ElMessage.success("新增成功");

    const childClassId = saveRes.data.classid;
    emit('update-node', {
      id: datas.dockid_info,
      property: 'categorySaveClass',
      value: childClassId
    });

    // 3. 恢复选中状态
    nextTick(() => {
      treeRef.value?.setCheckedKeys(checkedKeys);
      halfCheckedKeys.forEach(key => {
        const node = treeRef.value?.getNode(key);
        if (node) {
          treeRef.value?.setChecked(key, false, false);
        }
      });
    });


    // 4. 获取商品列表（如果有）
    const form11 = {
      id: dockIds.value,
      class: datas.classid,
      listid: parentId,
      page: currentPage.value,
      limit: 100,
    }
console.log(111111111122,form11)
    const listRes = await categorygoodlist(form11);

    // 修改这里：不再把"暂无数据"当作错误
    if (listRes.code === 200 || listRes.code === 1) {
		
      selectedAllItems.value = listRes.code === 200 ? listRes.data.data : [];
      selectedItems.value = listRes.code === 200 ? listRes.data.data : [];

      if (selectedAllItems.value.length !== 0) {
        await addPLDockGood(childClassId, form11);
      }
    } else {
      console.error("获取商品列表失败:", listRes.message);
    }
  } catch (error) {
    console.error("子级保存失败:", error);
    ElMessage.error("操作失败: " + error.message);
    throw error;
  }
}



//一键克隆的功能
//父级调用categorySave  这里需要看多选，变成遍历的
async function parentCategorySave_isBd3() {
  // 1. 保存当前选中状态
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];

  for (const [index, x] of checkDataList.value.entries()) {
    let form = {
      id: "",
      color: "",
      name: x.name,
      parent_id: 0,
      status: 1,
      pub_status: 1,
      istop: 1,
      info: "",
      dockid: dockIds.value,
      toOss:toOss.value,
      dockid_info: x.id,
      img:x.img,
      provide_type: ""
    };

    try {
      console.log(9999999,form)
      // 等待父级保存完成
      const res = await categorySave(form);
      categoryForm.value.parent_id = res.data.classid;
      categoryForm.value.img = res.data.cate_img;
      if (res.code == 200) {
        // 通知父组件更新对应节点
        emit('update-node', {
          id: x.id,
          property: 'categorySaveClass',
          value: res.data.classid
        });

        // 恢复选中状态
        nextTick(() => {
          treeRef.value?.setCheckedKeys(checkedKeys);
          halfCheckedKeys.forEach(key => {
            const node = treeRef.value?.getNode(key);
            if (node) {
              treeRef.value?.setChecked(key, false, false);
            }
          });
        });

        // 处理子级，使用 try-catch 包裹每个子项的处理
        for (const [index1, y] of x.list.entries()) {
          try {
            let formChild = {
              id: "",
              color: "",
              name: y.name,
              parent_id: res.data.classid,
              status: 1,
              pub_status: 1,
              istop: 1,
              info: "",
              dockid: dockIds.value,
              toOss:toOss.value,
              dockid_info: y.id,
              img:y.cate_img,
              provide_type: 1
            };
            categoryForm.value = formChild;
            console.log(8888888,formChild)
            await childCategorySave_isBd3(y, x.id);
          } catch (error) {
            console.error(`处理子项 ${y.id} 失败:`, error);
            // 继续处理下一个子项
            continue;
          }
        }
      }
    } catch (error) {
      console.error(`处理父项 ${x.id} 失败:`, error);
      // 继续处理下一个父项
      continue;
    }
  }
}
// 子级保存函数（修改为异步）
async function childCategorySave_isBd3(datas, parentId) {
  // 1. 保存当前选中状态
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];

  try {
    // 1. 保存子类
    const saveRes = await categorySave(categoryForm.value);

    if (saveRes.code !== 200) {
      throw new Error("子类保存失败");
    }

    ElMessage.success("新增成功");

    const childClassId = saveRes.data.classid;
    emit('update-node', {
      id: datas.id,
      property: 'categorySaveClass',
      value: childClassId
    });

    // 3. 恢复选中状态
    nextTick(() => {
      treeRef.value?.setCheckedKeys(checkedKeys);
      halfCheckedKeys.forEach(key => {
        const node = treeRef.value?.getNode(key);
        if (node) {
          treeRef.value?.setChecked(key, false, false);
        }
      });
    });

return
    // 4. 获取商品列表（如果有）
    const form11 = {
      id: dockIds.value,
      class: datas.classid,
      listid: datas.id,
      page: currentPage.value,
      limit: 100,
    }

    const listRes = await categorygoodlist(form11);

    // 修改这里：不再把"暂无数据"当作错误
    if (listRes.code === 200 || listRes.code === 1) {
      selectedAllItems.value = listRes.code === 200 ? listRes.data.data : [];
      selectedItems.value = listRes.code === 200 ? listRes.data.data : [];

      if (selectedAllItems.value.length !== 0) {
        await addPLDockGood(childClassId, form11);
      }
    } else {
      console.error("获取商品列表失败:", listRes.message);
    }
  } catch (error) {
    console.error("子级保存失败:", error);
    ElMessage.error("操作失败: " + error.message);
    throw error;
  }
}


//父级调用categorySave  这里需要看多选，变成遍历的
async function parentCategorySave() {
  // 1. 保存当前选中状态
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];

  for (const [index, x] of checkDataList.value.entries()) {
    let form = {};
    if (isBd.value == 1) {
      form = {
        id: "",
        color: "",
        name: x.name,
        parent_id: 0,
        status: 1,
        pub_status: 1,
        istop: 1,
        info: "",
        dockid: dockIds.value,
        toOss:toOss.value,
        dockid_info: x.id,
        img: imgListsting.value,
        provide_type: ""
      };
    } else if (isBd.value == 2) {
      form = {
        id: "",
        color: "",
        name: x.name,
        parent_id: 0,
        status: 1,
        pub_status: 1,
        istop: 1,
        info: "",
        dockid: dockIds.value,
        toOss:toOss.value,
        dockid_info: x.id,
        img: imgListsting.value,
      };
    }

    try {
      // 等待父级保存完成
      const res = await categorySave(form);
      categoryForm.value.parent_id = res.data.classid;
      categoryForm.value.img = res.data.cate_img;
      if (res.code == 200) {
        // 通知父组件更新对应节点
        emit('update-node', {
          id: x.id,
          property: 'categorySaveClass',
          value: res.data.classid
        });

        // 恢复选中状态
        nextTick(() => {
          treeRef.value?.setCheckedKeys(checkedKeys);
          halfCheckedKeys.forEach(key => {
            const node = treeRef.value?.getNode(key);
            if (node) {
              treeRef.value?.setChecked(key, false, false);
            }
          });
        });

        // 处理子级，使用 try-catch 包裹每个子项的处理
        for (const [index1, y] of x.list.entries()) {
          try {
            let formChild = {};
            if (isBd.value == 1) {
              formChild = {
                id: "",
                color: "",
                name: y.name,
                parent_id: res.data.classid,
                status: 1,
                pub_status: 1,
                istop: 1,
                info: "",
                dockid: dockIds.value,
                toOss:toOss.value,
                dockid_info: y.id,
                img:y.cate_img,
                provide_type: ""
              };
            } else if (isBd.value == 2) {
              formChild = {
                id: "",
                color: "",
                name: y.name,
                parent_id: res.data.classid,
                status: 1,
                pub_status: 1,
                istop: 1,
                info: "",
                dockid: dockIds.value,
                toOss:toOss.value,
                dockid_info: y.id,
                img: y.cate_img,
              };
            }

            categoryForm.value = formChild;
            await childCategorySave(y, x.id);
          } catch (error) {
            console.error(`处理子项 ${y.id} 失败:`, error);
            // 继续处理下一个子项
            continue;
          }
        }
      }
    } catch (error) {
      console.error(`处理父项 ${x.id} 失败:`, error);
      // 继续处理下一个父项
      continue;
    }
  }
}

// 子级保存函数（修改为异步）
async function childCategorySave(datas, parentId) {
  // 1. 保存当前选中状态
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];

  try {
    // 1. 保存子类
    const saveRes = await categorySave(categoryForm.value);

    if (saveRes.code !== 200) {
      throw new Error("子类保存失败");
    }

    ElMessage.success("新增成功");

    const childClassId = saveRes.data.classid;
    emit('update-node', {
      id: datas.id,
      property: 'categorySaveClass',
      value: childClassId
    });

    // 恢复选中状态
    nextTick(() => {
      treeRef.value?.setCheckedKeys(checkedKeys);
      halfCheckedKeys.forEach(key => {
        const node = treeRef.value?.getNode(key);
        if (node) {
          treeRef.value?.setChecked(key, false, false);
        }
      });
    });

    const form11 = {
      id: dockIds.value,
      class: datas.classid,
      listid: datas.id,
      page: currentPage.value,
      limit: 100,
    }

    // 2. 获取商品列表
    const listRes = await categorygoodlist(form11);

    // 修改这里：不再把"暂无数据"当作错误
    if (listRes.code === 200 || listRes.code === 1) {
      selectedAllItems.value = listRes.code === 200 ? listRes.data.data : [];
      selectedItems.value = listRes.code === 200 ? listRes.data.data : [];

      if (selectedAllItems.value.length !== 0) {
        await addPLDockGood(childClassId, form11);
      }
    } else {
      console.error("获取商品列表失败:", listRes.message);
    }
  } catch (error) {
    console.error("子级保存失败:", error);
    ElMessage.error("操作失败: " + error.message);
    throw error;
  }
}

// 批量自营或者批量对接的add接口
const multiplAdd = async () => {
  console.log('这个方法走了吗',multipleSelection.value)
  try {
    // 批量对接
    const loading = ElLoading.service({
      lock: true,
      text: `正在${dropdownData.value}商品 (0/${multipleSelection.value.length})`,
      background: "rgba(0, 0, 0, 0.7)",
    });
shoppingShow.value=false
    for (let i = 0; i < multipleSelection.value.length; i++) {
      try {
        loading.setText(`正在处理 ${i + 1}/${multipleSelection.value.length}`);

          let payload = {}
           if(dropdownData .value=='批量对接'){

             payload = {
               ...formLabelAlign.value,
               id: multipleSelection.value[i].id,
             };

           }else{
             payload = {
                 ...formLabelAlign.value,
                 id:multipleSelection.value[i].id,
                 provide_type:""
               };
           }
        
        await addDockGoods(payload);
        selectedItems.value.map((j,index)=>{
          if(j.id==multipleSelection.value[i].id){
             selectedItems.value[index]._has_join=true

          }
        })

		// const listRes = await categorygoodlist(form11);
		// selectedItems.value = listRes.data.data || [];
        // if (i < selectedAllItems.value.length - 1) {
        //   await new Promise((resolve) => setTimeout(resolve, 300));
        // }
      } catch (error) {
        // console.error(`商品 ${multipleSelection.value[i].id} 对接失败:`, error);
        // ElMessage.error(`商品 ${multipleSelection.value[i].id} 对接失败`);
      }
    }

    loading.close();
    ElMessage.success(
      `批量对接完成，共处理 ${multipleSelection.value.length} 个商品`
    );
	  // await getSetdocking();
  } catch (error) {
    console.error("批量对接操作失败:", error);
    ElMessage.error("批量对接过程中出现错误");
    throw error; // 重新抛出错误，让调用者处理
  }
};

const imgList=ref([])
const imgList2=ref([])
const idshow=ref("")
const imgListsting=ref("")
const imgListsting2=ref("")
const addDockGood = async () => {
  console.log('sdsd',imgListsting2.value)
  categoryForm2.value.img =  imgListsting2.value; //里面的图片
  categoryForm.value.img =  imgListsting.value;  //外面一层的图片
  console.log('一级图片',imgListsting.value,'二级图片',imgListsting2.value)
  
  if(mobanShow.value == '' && idshow.value !==3){
    ElMessage({
    message: '请选择加价模版',
    type: 'warning',
  })
      return
  }
  console.log('测试',categoryForm2.value)
  
  try {
    const cateids = formLabelAlign.value.cate_id;
    // formLabelAlign.value.cate_ids = [cateids];
    console.log(11111111111, dockId.value);
    formLabelAlign.value.Docking = dockIds.value; //81 // 实际替换 dockId.value
    // 如果有右侧的下拉菜单点击
if(isDropdown.value){
  console.log(999991111,isDropdown.value)
 
multiplAdd()
return
}
    if (ispldj.value) {
      // 单个对接
      await addDockGoods(formLabelAlign.value).then((res=>{
         ElMessage.success(res.msg); // 现在可以正常使用
      }));
 getSetdocking();
      shoppingShow.value=false
      return
    } else {
      try {
        // 1. 首先调用 categorySave 接口
 shoppingShow.value = false;
 if(isBd.value==3){
	 console.log(222259858)
   parentCategorySave_isBd3()  //本地克隆
 }else if(isBd.value==4){
	 console.log(8888999)
	 const cateids = formLabelAlign.value.cate_id;
	 formLabelAlign.value.cate_ids = [cateids];
	 parentCategorySave_isBd4()  
 }else if(isBd.value==5){
	 console.log(8888999)
	 const cateids = formLabelAlign.value.cate_id;
	 formLabelAlign.value.cate_ids = [cateids];
	 parentCategorySave_isBd5()  
 }
 
 else{
   parentCategorySave();
 }

        // const ress = await categorySave(categoryForm.value);

        // // 2. 只有在 categorySave 成功后才继续执行
        // if (ress.code == 200) {
        //   ElMessage.success("新增成功"); // 现在可以正常使用

        //   // 3. 调用 addPLDockGood 并等待它完成
        //   await addPLDockGood(ress.data.classid);

        //   // 4. 其他后续操作
        //   getSetdocking();
        //   shoppingShow.value = false;
        // }
      } catch (error) {
        console.error("分类保存失败:", error);
        ElMessage.error("分类保存失败");
        throw error; // 重新抛出错误，让外层 catch 捕获
      }
    }
  } catch (error) {
    console.error("对接操作失败:", error);
    ElMessage.error("对接过程中出现错误");
  }
};
// 获取批量的是所有接口调取checkedChildrenIdList
const selectedAllItems=ref([])
const getCheckAllSetdocking = () => {
  tableLoading.value = true;
  // treeLoading.value = true // 如果树加载也需要

  // 创建存储所有请求的Promise数组
  const promises = checkedChildrenIdList.value.map(x => {
    const form = {
      id: dockIds.value,
      class: x.classid,
      listid: x.id,
      page: currentPage.value,
      limit:100,
    };
    return categorygoodlist(form);
  });

  // 使用Promise.all等待所有请求完成
  Promise.all(promises)
    .then(responses => {
      // 合并所有成功响应的数据
      const allItems = [];
      let totalCount = 0;

      responses.forEach(res => {
        if (res.code === 200) {
          // 合并当前响应的数据到总数组
          if (res.data.data && res.data.data.length > 0) {
            allItems.push(...res.data.data);
          }
          // 累加总数（根据实际需求选择是否累加）
          totalCount += res.data.count || 0;
        } else {
          console.error("获取商品列表失败:", res.message);
        }
      });

      // 更新响应式数据
      selectedAllItems.value = allItems;
      total.value = totalCount; // 或保持原逻辑：total.value = allItems.length
    })
    .catch(error => {
      console.error("接口调用错误:", error);
      selectedItems.value = [];
      total.value = 0;
    })
    .finally(() => {
      tableLoading.value = false;
      // treeLoading.value = false // 如果树加载也需要
    });
};

// 修改后的批量对接函数，接受 classid 参数
const addPLDockGood = async (classid?: string,form11) => {
  try {
    // 批量对接取消商品
    formLabelAlign.value.cate_id = "";

    // 如果有传入 classid，设置到表单中
    if (classid) {
      formLabelAlign.value.cate_ids = [classid];
    }

    // 批量对接
    const loading = ElLoading.service({
      lock: true,
      text: `正在批量对接商品 (0/${selectedAllItems.value.length})`,
      background: "rgba(0, 0, 0, 0.7)",
    });

    for (let i = 0; i < selectedAllItems.value.length; i++) {
      try {
        loading.setText(`正在处理 ${i + 1}/${selectedAllItems.value.length}`);

  let payload = {}
   if(isBd.value==1){

     payload = {
       ...formLabelAlign.value,
       id: selectedAllItems.value[i].id,
       provide_type:""
     };

   }else if(isBd.value==2){
      payload = {
       ...formLabelAlign.value,
       id: selectedAllItems.value[i].id,
     };

   }else{
     payload = {
         ...formLabelAlign.value,
         id: selectedAllItems.value[i].id,
         provide_type:""
       };


   }

        await addDockGoods(payload);
        selectedItems.value[i]._has_join=true
		// const listRes = await categorygoodlist(form11);
		// selectedItems.value = listRes.data.data || [];
        // if (i < selectedAllItems.value.length - 1) {
        //   await new Promise((resolve) => setTimeout(resolve, 300));
        // }
      } catch (error) {
        console.error(`商品 ${selectedAllItems.value[i].id} 对接失败:`, error);
        ElMessage.error(`商品 ${selectedAllItems.value[i].id} 对接失败`);
      }
    }

    loading.close();
    ElMessage.success(
      `批量对接完成，共处理 ${selectedAllItems.value.length} 个商品`
    );
	  // await getSetdocking();
  } catch (error) {
    console.error("批量对接操作失败:", error);
    ElMessage.error("批量对接过程中出现错误");
    throw error; // 重新抛出错误，让调用者处理
  }
};
// 新增：文字点击事件处理
const handleNodeLabelClick = (node: any, data: any) => {
  console.log("点击节点文字:", data);
  // 示例：点击文字时展开/收起子节点
  if (node.children && node.children.length > 0) {
    node.expanded = !node.expanded;
  }
};
// 处理复选框变化
const handleCheckboxChange = (val: boolean, node: any) => {
  // 手动设置节点的选中状态
  treeRef.value?.setChecked(node.key, val, true);
  updateSelectedStatus();
};

// 处理文字点击（不操作复选框）
const cheshi=ref('')
const classids2=ref("")
const handleLabelClick = (data: any) => {
  console.log("点击了文字:", data, "12121212", categoryForm.value.dockid_info,props.treeData);
  categoryForm.value.dockid_info=data.id
 categoryForm2.value.dockid_info=data.classid
  classids2.value=data.classid
  //获取名字
  for(let item of props.treeData){
	  console.log('1212121',item.id)
	  if( classids2.value==item.id){
		  categoryForm2.value.name=item.name
      categoryForm2.value.img=item.cate_img
	  }

  }
    console.log('多发点发放的',categoryForm2.value.name)
  form1.value = {
    id: dockIds.value, //81,
    class: data.classid,
    listid: data.id,
    page: currentPage.value,
    limit: pageSize.value,
  };
  categoryForm.value.dockid = dockIds.value;
  categoryForm2.value.dockid = dockIds.value;
  categoryForm2.value.img =  data.cate_img;
  categoryForm.value.name = data.name;
  if (data.classid) {
    // categoryForm.value.parent_id=data.classid
    //categoryForm.value.dockid_info = data.classid;
  } else {
    // categoryForm.value.parent_id=0
    categoryForm.value.dockid_info = data.id;
  }
  console.log("categoryForm.value", categoryForm.value);
  //调接口

  getSetdocking();

  // 调用接口

  // 这里执行你的自定义逻辑，比如：
  // 1. 显示详情
  // showNodeDetails(data);

  // 2. 展开/折叠节点
  // const treeNode = treeRef.value?.getNode(data.id);
  // if (treeNode) treeNode.expanded = !treeNode.expanded;

  // 3. 其他业务逻辑...
};
function getLocalCatePageList() {
  getLocalCatePage().then((res) => {
    if (res.code == 200) {
      dockingMenuList.value = res.data;
    }
  });
}
function getGoodPriceReadyPage() {
  getGoodPriceReadyList().then((res) => {
    if (res.code == 200) {
      goodPriceReadyList.value = res.data;
    }
  });
}
// 分页相关方法也需要添加 loading
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  form1.value.limit = val; // 确保更新form1中的limit
  tableLoading.value = true;
  getSetdocking();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
   form1.value.page = val; // 确保更新form1中的page
  tableLoading.value = true;
  getSetdocking();
};
const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};
// 默认数据
const data: Tree[] = [
  {
    id: 1,
    label: "Level one 1",
    children: [
      {
        id: 4,
        label: "Level two 1-1",
        children: [
          { id: 9, label: "Level three 1-1-1" },
          { id: 10, label: "Level three 1-1-2" },
        ],
      },
    ],
  },
  {
    id: 2,
    label: "Level one 2",
    children: [
      { id: 5, label: "Level two 2-1" },
      { id: 6, label: "Level two 2-2" },
    ],
  },
  {
    id: 3,
    label: "Level one 3",
    children: [
      { id: 7, label: "Level two 3-1" },
      { id: 8, label: "Level two 3-2" },
    ],
  },
];

// 获取当前树的所有节点ID
const getAllKeys = (nodes: Tree[]): number[] => {
  return nodes.flatMap((node) => [
    node.id,
    ...(node.children ? getAllKeys(node.children) : []),
  ]);
};

// 全选
const setCheckedKeys = () => {
  nextTick(() => {
    if (treeRef.value) {
      const targetData = props.treeData.length ? props.treeData : data;
      const allKeys = getAllKeys(targetData);
      treeRef.value.setCheckedKeys(allKeys);
    }
  });
};
// 新增：选中状态变化事件处理
const handleCheckChange = (
  data: any,
  checked: boolean,
  indeterminate: boolean
) => {
  console.log(
    "复选框状态变化:",
    data,
    "选中:",
    checked,
    "半选:",
    indeterminate
  );

  // 可选：实时更新选中状态
  updateSelectedStatus();
};
const checkedChildrenId=ref('')
const checkedChildrenIdList=ref([])
const parentIds =ref('')
const checkDataList=ref([]) //选中以后过滤的数据
// 可选：更新选中状态的方法
const updateSelectedStatus = async () => {
  if (treeRef.value) {
    // 获取所有选中的节点（包括半选中节点）
    const checkedNodes = treeRef.value.getCheckedNodes(false, true); // 提取选中节点的ID

    // 获取半选中节点的keys
    const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();

    console.log("选中的节点:", checkedNodes);
    console.log("半选中的节点:", halfCheckedKeys);
    const listIds = checkedNodes.map((node) => node.id).join(",");

    // 提取选中父级节点的ID（有子节点的节点）
    console.log("checkedNodes111:", checkedNodes);
    checkedNodesAll.value = checkedNodes;
    console.log(" checkedNodes.value:", checkedNodesAll.value);
    // 提取子id
    const checkedChildrenId=[]
       checkedNodes.map((item) => {if(item.classid){checkedChildrenId.push(item)}});
       checkedChildrenIdList.value=checkedChildrenId
       checkedChildrenId.value=[...checkedNodes].join(",");
    // 提取所有classid
    const classIds = checkedNodes.map((item) => item.classid);
     const checkedParentList=[]
  checkedNodes.map((item) => {if(!item.classid){checkedParentList.push(item)}});


  // 1. 创建查找键（使用 id + classid 组合）
  const lookupKeys = new Set();
  checkedChildrenId.forEach(item => {
    lookupKeys.add(`${item.id}_${item.classid}`);
  });

  // 2. 对 arr1 中的每个对象过滤其 list 数组
  const result = checkedParentList.map(item => {
    // 过滤当前对象的 list 数组
    const filteredList = item.list.filter(listItem => {
      const key = `${listItem.id}_${listItem.classid}`;
      return lookupKeys.has(key);
    });

    // 返回新对象（包含过滤后的 list）
    return {
      ...item,
      list: filteredList
    };
  });
 checkDataList.value=result
  console.log('22222222222222222222222222222222222',result);
  imgList.value=[]
  imgList2.value=[]
  for(let item of result){
    imgList.value.push(item.cate_img)
    for(let item2 of item.list){
      imgList2.value.push(item2.cate_img)
    }
  }
  imgListsting.value=imgList.value.join(',')
  imgListsting2.value=imgList2.value.join(',')
  console.log('111111111111111111111',imgList.value,imgListsting2.value);
  multipleSelection.value=result

     console.log('asdfasdfasdfasdfsdfa',checkedParentList)
        console.log('rtyurtyurtyutry',checkedChildrenId)
    // 使用Set去重
    const uniqueClassIds = new Set(classIds);
    // 转换为数组并使用逗号连接
    const parentId = [...uniqueClassIds].join(",");
    parentIds.value=parentId
    // form1.value = {
    //   id: 81, //dockId.value
    //   class: parentIds,
    //   listid: listIds,
    //   page: currentPage.value,
    //   limit: pageSize.value
    // }
  }
};
// 监听 treeData 变化，显示加载状态
// 监听 treeData 变化
watch(
  () => props.treeData,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      treeLoading.value = true;
      // 使用 nextTick 确保 DOM 更新完成
      nextTick(() => {
        // 模拟渲染时间，实际项目中可以去掉 setTimeout
        setTimeout(() => {
          treeLoading.value = false;
        }, 300);
      });
    }
  },
  { immediate: true }
);
// 监听对话框打开状态
watch(
  () => props.modelValue,
  (newVal) => {
    dialogVisible.value = newVal;

    if (newVal) {
      // 对话框打开时重置状态
      input1.value = "";
      if (treeRef.value) {
        treeRef.value.setCheckedKeys([]);
      }
    }
  }
);
// 在获取商品列表时也添加 loading
// 修改 getSetdocking 方法
const getSetdocking = () => {
  console.log(form1.value)
  tableLoading.value = true; // 表格加载开始
  // treeLoading.value = true // 树加载开始（如果也需要）

  categorygoodlist(form1.value)
    .then((res) => {
      if (res.code == 200) {
        selectedItems.value = res.data.data || [];
        total.value = res.data.count || 0;
      } else {
        console.error("获取商品列表失败:", res.message);
        selectedItems.value = [];
        total.value = 0;
      }
    })
    .catch((error) => {
      console.error("接口调用错误:", error);
      selectedItems.value = [];
      total.value = 0;
    })
    .finally(() => {
      tableLoading.value = false; // 表格加载结束
      // treeLoading.value = false // 树加载结束（如果也需要）
    });
};

// 反选
const setCheckedKeysShow = () => {
  nextTick(() => {
    if (treeRef.value) {
      const targetData = props.treeData.length ? props.treeData : data;
      const allKeys = getAllKeys(targetData);
      const checkedKeys = treeRef.value.getCheckedKeys();
      const newCheckedKeys = allKeys.filter(
        (key) => !checkedKeys.includes(key)
      );
      treeRef.value.setCheckedKeys(newCheckedKeys);
    }
  });
};

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
  expandShow.value = isExpanded.value;

  nextTick(() => {
    if (!treeRef.value) return;

    const targetData = props.treeData.length ? props.treeData : data;
    const nodesMap = treeRef.value.store.nodesMap;

    Object.values(nodesMap).forEach((node: any) => {
      node.expanded = expandShow.value;
    });
  });
};

// 树节点点击事件
const handleNodeClick = (data: any) => {
  console.log("选中节点:", data);
};

// 过滤函数
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.includes(value);
};

// 生命周期钩子：组件挂载后初始化
onMounted(() => {
  checkIsMobile()
    window.addEventListener('resize', checkIsMobile)
  nextTick(() => {
    if (treeRef.value) {
      treeRef.value.filterNodeMethod = filterNode;
      treeLoaded.value = true;
    }
  });
});
onBeforeUnmount(() => {
  window.removeEventListener('resize', checkIsMobile)
})
// 监听对话框打开状态
watch(
  () => props.modelValue,
  (newVal) => {
    dialogVisible.value = newVal
    if (newVal && isMobile.value) {
      // 移动端打开对话框时默认隐藏树
      showTree.value = false
    }
  }
)
//添加加价模版
function addPrice(){
  priceShow.value=true
}
function mobanClose(){
  priceShow.value=false
}
// 监听搜索输入
watch(input1, (newVal) => {
  if (treeRef.value) {
    treeRef.value.filter(newVal);
  }
});
watch(
  () => props.dockId,
  (newVal) => {
    console.log("接受的id", newVal);
    dockIds.value = newVal;
  }
);
// 监听父组件显示状态变化
watch(
  () => props.modelValue,
  (newVal) => {
    dialogVisible.value = newVal;

    if (newVal && treeRef.value && treeLoaded.value) {
      // 对话框打开时重置树状态
      nextTick(() => {
        const targetData = props.treeData.length ? props.treeData : data;
        const allKeys = getAllKeys(targetData);
        treeRef.value.setExpandedKeys(expandShow.value ? allKeys : []);
        treeRef.value.setCheckedKeys([]); // 清空选择状态
      });
    }
  },
  { immediate: true }
);

// 监听dialog状态同步到父组件
watch(dialogVisible, (newVal) => {
  emit("update:modelValue", newVal);
});

// 关闭处理
const handleClose = (done: () => void) => {
  done();
  // ElMessageBox.confirm('确定要关闭对接窗口吗？')

  //   .then(() => {
  //     done()
  //     dialogVisible.value = false
  //   })
  //   .catch(() => {
  //     // 取消关闭
  //   })
};

//文本溢出判断
const shouldShowTooltip = (text: string) => {
  const dummyElement = document.createElement('span');
  dummyElement.innerText = text;
  dummyElement.style.visibility = 'hidden';
  dummyElement.style.position = 'absolute';
  dummyElement.style.fontSize = '14px'; // 与表格字体大小保持一致

  document.body.appendChild(dummyElement);
  const isOverflow = dummyElement.offsetWidth > 120; // min-width为120px
  document.body.removeChild(dummyElement);

  return isOverflow;
}




// 取消处理
const handleCancel = () => {
  dialogVisible.value = false;
};

// 确认处理
const handleConfirm = () => {
  if (treeRef.value) {
    const checkedKeys = treeRef.value.getCheckedKeys();
    const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
    emit("confirm", { checkedKeys, halfCheckedKeys });
  }
  dialogVisible.value = false;
};
//判断本地是否显示
function getisBind7NiuYun(){
  isBind7NiuYun().then((res)=>{
    if(res.code == 200){
      imgName.value='转存到OSS'
    }else{
      imgName.value='未配置OSS'
    }
  })
}
//批量对接打卡弹框
function getbtnpi(e){
  shopping.value=true
console.log('这是啥',e)

idshow.value=e
for(let item of options){
  if(e == item.value){
    titleName.value=item.label
  }
}
}
const btnpi = (ids) => {
 console.log('重复的也调取')
 getisBind7NiuYun()
  if( multipleSelection.value.length>0){
    if(isBd.value ==3){
    modelShow.value=false
  }else{
    modelShow.value=false
  }
if(isBd.value==4){
	 ispldj.value = false;
	getLocalCatePageList();
	getGoodPriceReadyPage();
	 shoppingShow.value = true;
	return
}if(isBd.value==5){
	 ispldj.value = false;
	getLocalCatePageList();
	getGoodPriceReadyPage();
	 shoppingShow.value = true;
	return
}
  if (ids) {
    // 单个对接情况
    isDropdown.value=false
    ispldj.value = true;
    formLabelAlign.value.id = ids;
    getLocalCatePageList();
    getGoodPriceReadyPage();
    shoppingShow.value = true;
    return
  } else {
 if(isDropdown.value){
    getLocalCatePageList();
    getGoodPriceReadyPage();
    shoppingShow.value = true;
    return
  }else{
    ispldj.value = false;
    getGoodPriceReadyPage();
      shoppingShow.value = true;
  }
    console.log(checkedNodesAll.value);
      return
  }
  }else{
    ElMessage.error('请先选择分类')
  }
 
};



const btnpi2 = (ids) => {
 console.log('重复的也调取')
 getisBind7NiuYun()
  
    if(isBd.value ==3){
    modelShow.value=false
  }else{
    modelShow.value=false
  }
if(isBd.value==4){
	 ispldj.value = false;
	getLocalCatePageList();
	getGoodPriceReadyPage();
	 shoppingShow.value = true;
	return
}if(isBd.value==5){
	 ispldj.value = false;
	getLocalCatePageList();
	getGoodPriceReadyPage();
	 shoppingShow.value = true;
	return
}
  if (ids) {
    // 单个对接情况
    isDropdown.value=false
    ispldj.value = true;
    formLabelAlign.value.id = ids;
    getLocalCatePageList();
    getGoodPriceReadyPage();
    shoppingShow.value = true;
    return
  } else {
 if(isDropdown.value){
    getLocalCatePageList();
    getGoodPriceReadyPage();
    shoppingShow.value = true;
    return
  }else{
    ispldj.value = false;
    getGoodPriceReadyPage();
      shoppingShow.value = true;
  }
    console.log(checkedNodesAll.value);
      return
  }
  
};




</script>

<style scoped>
:deep .el-tree-node__content > label.el-checkbox {
  display: none !important;
}
:deep .el-tree-node__label {
  margin-top: 16px !important;
}
.header {
  background-color: white;
  padding: 0 0 1px 12px;
  border-radius: 8px;
}
:deep .el-tree-node__label {
  margin-top: 16px;
}

.inputs {
  text-align: center;
  margin-top: 12px;
}

.left-header {
  display: flex;
  justify-content: space-around;
  margin-top: 15px;
}

.contents {
  display: flex;
}

.contents-left {
  width: 30%;
  border: 1px solid #3333;
  padding-bottom: 30px;
}

.contents-rights {
  border: 1px solid #3333;
  width: 100%;
  height: 100%;
}

.contents-right {
  flex: 1;
  padding-left: 20px;
}
</style>

<style>
.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
}

.tree-checkbox-wrapper {
  /* 阻止事件冒泡并保持布局 */
  margin-right: 8px;
}

.tree-label {
  flex: 1;
  cursor: pointer;
  /* 可选悬停效果 */
}

/* 确保下拉面板可见 */
:deep(.el-tree-select__popper) {
  z-index: 9999 !important;
}

:deep(.el-tree-select__popper .el-tree) {
  min-width: 200px;
}

.custom-node {
  flex: 1;
  padding: 0 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}




.tree-label:hover {
  color: #409eff;
  text-decoration: underline;
}
/* 隐藏原生复选框（如果不需要双复选框） */
:deep .el-tree-node__content > label.el-checkbox {
  display: none !important;
}
:deep .el-tree-node__label {
  margin-top: 16px !important;
}

:deep .el-loading-spinner {
  top: 20%;
}

:deep .el-loading-spinner .el-icon-loading {
  font-size: 30px;
  color: #409eff;
}

:deep .el-loading-mask {
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 4px;
}

/* 添加表格 loading 样式 */
:deep .el-table .el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}

:deep .el-table .el-loading-spinner {
  top: 50%;
  transform: translateY(-50%);
}

:deep .el-table .el-loading-spinner .el-icon-loading {
  font-size: 36px;
  color: #409eff;
}

:deep .el-table .el-loading-spinner .el-loading-text {
  margin-top: 12px;
  font-size: 14px;
}

/* 确保半选中状态可见 */
:deep .el-checkbox__indeterminate .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
}

:deep .el-checkbox__indeterminate .el-checkbox__inner::before {
  background-color: white;
  height: 2px; /* 调整半选中状态的横线高度 */
  width: 60%; /* 调整半选中状态的横线宽度 */
}

/* 修复自定义复选框可能覆盖原生行为的问题 */
:deep .el-tree-node__content > .el-checkbox {
  margin-right: 8px;
}

/* 在子组件样式中添加 */
:deep .el-loading-mask {
  z-index: 2000; /* 确保在对话框上方 */
}

/* 调整树形组件的 loading 位置 */
:deep .el-tree .el-loading-spinner {
  top: 20%;
}

/* 省略号效果 */
.ellipsis-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

/* 定制工具提示最大宽度 */
.el-tooltip__popper {
  max-width: 300px;
  word-break: break-word;
}


.names{
	    display: inline-block;
	    width: 45px;
	    text-align: center;
	    height: 22px;
	    background: #e7faf0;
		color:#14a85a
}
.contents {
  display: flex;
  height: 60vh;
}

.contents-left {
  width: 23%;
  border: 1px solid #3333;
  padding-bottom: 30px;
  overflow: auto;
}
</style>
<style scoped>
/* 基础样式 */
.contents {
  display: flex;
  flex-direction: row;
  height: 60vh;
}

/* 左侧树形区域 */
.contents-left {
  width: 23%;
  border: 1px solid #eee;
  padding-bottom: 15px;
  overflow: auto;
  transition: all 0.3s;
}

/* 右侧内容区域 */
.contents-right {
  flex: 1;
  padding-left: 15px;
  overflow: auto;
}

/* 左侧头部 */
.left-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  margin-top: 10px;
  flex-wrap: wrap;
  gap: 8px;
}

/* 搜索输入框 */
.inputs {
  padding: 0 10px;
  margin-top: 10px;
}

/* 树形容器 */
.tree-container {
  margin-top: 10px;
  padding: 0 5px;
}

/* 自定义树节点 */
.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 5px 0;
}

.tree-checkbox-wrapper {
  margin-right: 8px;
}

.tree-label {
  flex: 1;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.label-text {
  display: inline-block;
  width: 126px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.names {
  display: inline-block;
  width: 45px;
  text-align: center;
  height: 22px;
  background: #e7faf0;
  color: #14a85a;
  margin-left: 5px;
  border-radius: 3px;
  font-size: 12px;
}

/* 表格区域 */
.table-area {
  margin-top: 15px;
}

/* 分页容器 */
.pagination-container {
  margin-top: 15px;
  text-align: center;
}

/* 对话框底部 */
.dialog-footer {
  text-align: center;
}

/* 图片选项区域 */
.image-options {
  margin-top: 15px;
}

.upload-area {
  margin-top: 10px;
}

/* 移动端样式 */
@media (max-width: 768px) {
  .contents {
    flex-direction: column;
    height: auto;
  }

  .contents-left {
    width: 100%;
    padding-bottom: 10px;
    margin-bottom: 10px;
  }

  .contents-right {
    padding-left: 0;
  }

  .mobile-tree-toggle {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px;
    background: #f5f7fa;
    margin-bottom: 10px;
    cursor: pointer;
    border-radius: 4px;
  }

  .mobile-hidden {
    display: none;
  }

  .left-header {
    justify-content: space-around;
    gap: 5px;
  }

  .label-text {
    width: 50px;
  }

  .names {
    width: 40px;
    font-size: 11px;
  }

  /* 表格在小屏幕上缩小字体 */
  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-table td),
  :deep(.el-table th) {
    padding: 4px 0;
  }

  /* 分页在小屏幕上简化 */
  :deep(.el-pagination) {
    white-space: nowrap;
  }

  :deep(.el-pagination__total),
  :deep(.el-pagination__sizes),
  :deep(.el-pagination__jump) {
    display: none;
  }
}

/* PC端特定样式 */
@media (min-width: 769px) {
  .mobile-tree-toggle {
    display: none;
  }
}

</style>
